<template>
  <div class="app-container">
    <!--条件栏-->
    <el-form :model="queryParams" ref="queryForm" :rules="queryForm" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="合同编号" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合同编号"
          clearable
          size="small"
          maxlength="30"
          show-word-limit
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="甲方" prop="contractJia">
        <el-input
          v-model="queryParams.contractJia"
          placeholder="请输入甲方"
          clearable
          size="small"
          maxlength="30"
          show-word-limit
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="乙方" prop="contractYi">
        <el-input
          v-model="queryParams.contractYi"
          placeholder="请输入乙方"
          clearable
          size="small"
          maxlength="30"
          show-word-limit
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同类型" prop="contractType">
        <el-select v-model="queryParams.contractType" placeholder="请选择合同类型" clearable
                   size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同分类" prop="contractBanner">
        <el-select v-model="queryParams.contractBanner" placeholder="请输入合同分类" clearable
                   size="small">
          <el-option
            v-for="dict in bannerOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--操作栏-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['server:contract:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['server:contract:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['server:contract:export']"
        >导出
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!--合同信息列表-->
    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="序号" type="index" align="center" prop="contractId"/>
      <el-table-column label="合同编号" align="center" prop="contractCode"/>
      <el-table-column label="甲方" align="center" prop="contractJia"/>
      <el-table-column label="乙方" align="center" prop="contractYi"/>
      <el-table-column label="附件" align="center" prop="contractEnclosure">
        <template slot-scope="scope">
          {{getFileListName(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column label="合同类型" align="center" prop="contractType" :formatter="contractTypeFormat"/>
      <el-table-column label="合同分类" align="center" prop="contractBanner" :formatter="contractBannerFormat"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['server:contract:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['server:contract:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运营管理合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="合同编号:" prop="contractCode" style="width:85%">
          <el-input v-model="form.contractCode" placeholder="请输入合同编号" maxlength="30"/>
        </el-form-item>
        <el-form-item label="甲方:" prop="contractJia" style="width:85%">
          <el-input v-model="form.contractJia" placeholder="请输入甲方" maxlength="30"/>
        </el-form-item>
        <el-form-item label="乙方:" prop="contractYi" style="width:85%">
          <el-input v-model="form.contractYi" placeholder="请输入乙方" maxlength="30"/>
        </el-form-item>


        <el-form-item label="附件:" prop="contractEnclosure" style="width:85%">
          <el-upload style="margin-top: -5px"
                     class="upload-demo"
                     :action="url"
                     :on-remove="handleRemove"
                     :on-change="handleChange"
                     :before-upload="beforeUpload"
                     :before-remove="beforeRemove"
                     :auto-upload="false"
                     multiple
                     :on-preview="handlePreview"
                     :on-exceed="handleExceed"
                     :limit="3"
                     :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip" style="display: inline-block;margin-left: 10px;font-size: 10px">
              支持.word/.png/.pdf/jpg文件
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="合同类型:" prop="contractType">
          <el-select v-model="form.contractType" placeholder="请选择合同类型" style="width: 81%">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同分类:" prop="contractBanner">
          <el-select v-model="form.contractBanner" placeholder="请输入合同分类" style="width: 81%">
            <el-option
              v-for="dict in bannerOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="备注:" prop="remark" style="width:85%">
          <el-input v-model="form.remark" placeholder="请输入备注" maxlength="200"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listContract,
    getContract,
    delContract,
    addContract,
    updateContract,
    exportContract
  } from '@/api/server/operate/contract'

  export default {
    name: 'Contract',
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 运营管理合同表格数据
        contractList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        typeOptions: [],
        bannerOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          contractCode: null,
          contractJia: null,
          contractYi: null,
          contractEnclosure: null,
          contractType: null,
          contractBanner: null
        },
        // 表单参数
        form: {}
        ,
        //列信息
        columns: [
          {key: 0, label: "序号", visible: true},
          {key: 1, label: "合同编号", visible: true},
          {key: 2, label: "甲方", visible: true},
          {key: 3, label: "乙方", visible: true},
          {key: 4, label: "附件", visible: true},
          {key: 5, label: "合同类型", visible: true},
          {key: 6, label: "合同分类", visible: true},
          {key: 7, label: "备注", visible: true},
        ],
        queryForm: {
          contractJia: [{pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不能为特殊字符', trigger: 'blur'}],
          contractYi: [{pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不能为特殊字符', trigger: 'blur'}],
        },
        // 表单校验
        rules: {
          contractCode: [{
            required: true, message: '合同编号不能为空', trigger: 'blur'
          }
          ],
          contractJia: [{
            required: true,
            message: "甲方不能为空",
            trigger: "blur"
          }],
          contractYi: [{
            required: true,
            message: "乙方不能为空",
            trigger: "blur"
          }],
          contractType: [{
            required: true,
            message: "合同类型不能为空",
            trigger: "change"
          }],
          contractBanner: [{
            required: true,
            message: "合同分类不能为空",
            trigger: "change"
          }],
        },
        //附件上传列表
        fileList: [],
        url: process.env.VUE_APP_BASE_API + '/server/contract', // 这里写上传文件的地址
      }

    },
    created() {
      this.getList()
      this.getDicts("t_contract_type").then(response => {
        this.typeOptions = response.data;
      })
      this.getDicts("t_contract_banner").then(response => {
        this.bannerOptions = response.data;
      })
    },
    methods: {
      handleChange(file, fileList) {
        this.fileList = fileList
      },
      beforeUpload(file) {
        console.log(file)
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
        this.fileList.splice(file, 1)
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      /** 查询运营管理合同列表 */
      getList() {
        this.loading = true
        listContract(this.queryParams).then(response => {
          this.contractList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      //获取上传文件列表名单
      getFileListName(data) {
        let result = data.contractEnclosure
        if (data.contractEnclosure != null) {
          let arr = data.contractEnclosure.split(",")
          let list = []
          for (let fileName of arr) {
            if (fileName.indexOf("-") > -1) {
              let substring = fileName.substring(fileName.lastIndexOf("-") + 1, fileName.length);
              list.push(substring);
            }
          }
          if (list.length > 0) {
            result = list.join(",")
          }
        }
        return result

      },
      //获取上传文件列表
      getFileList(data) {
        let result = data.contractEnclosure
        if (data.contractEnclosure != null && data.contractEnclosure != '') {
          let arr = data.contractEnclosure.split(",")
          let list = []
          if (arr.length > 0) {
            for (let fileName of arr) {
              if (fileName.indexOf("-") > -1) {
                let obj = {}
                let substring = fileName.substring(fileName.lastIndexOf("-") + 1, fileName.length);
                obj.name = substring
                obj.url = fileName
                list.push(obj);
              } else {
                let obj = {}
                obj.name = fileName
                obj.url = fileName
                list.push(obj);
              }
            }
          }
          this.fileList = list
        }
        return result
      },
      // 状态字典翻译
      contractTypeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.contractType)
      },
      contractBannerFormat(row, column) {
        return this.selectDictLabel(this.bannerOptions, row.contractBanner)
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
        this.clearFileList()
      },
      // 表单重置
      reset() {
        this.form = {
          contractId: null,
          contractCode: null,
          contractJia: null,
          contractYi: null,
          contractEnclosure: null,
          contractType: null,
          contractBanner: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        }

        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.$refs['queryForm'].validate(valid => {
          if (valid) {
            this.getList()
          }
        })
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.contractId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加运营管理合同'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const contractId = row.contractId || this.ids
        getContract(contractId).then(response => {
          let data = response.data
          this.getFileList(data)
          this.form = response.data
          this.open = true
          this.title = '修改运营管理合同'
          console.log(this.fileList)

        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
            if (valid) {
              let formData = new FormData()
              for (let key in this.form) {
                if (this.form[key] != null && key != 'params') formData.append(key, this.form[key])
              }
              let arr = []
              if (this.fileList.length != 0) {
                this.fileList.forEach(file => {
                  arr.push(file.name)
                  formData.append('file', file.raw)
                })
              }
              formData.append("fileList", arr.join(','))


              if (this.form.contractId != null) {
                updateContract(formData).then(response => {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                  this.clearFileList()
                })
              } else {
                addContract(formData).then(response => {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                  this.clearFileList()
                })
              }
            }
          }
        )
      },
      clearFileList() {
        this.fileList = []
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const contractIds = row.contractId || this.ids
        this.$confirm('是否确认删除该数据项?', '警告', {
          cancelButtonClass: 'btn-custom-cancel',
          closeOnClickModal: false,
          type: 'warning'
        }).then(function () {
          return delContract(contractIds)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有运营管理合同数据项?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(function () {
          return exportContract(queryParams)
        }).then(response => {
          this.download(response.msg)
        })
      }
    }
  }
</script>
